package logger

import (
	"errors"
	"fmt"
	"github.com/mattn/go-colorable"
	"github.com/sirupsen/logrus"
	"goadmin/config"
	"log"
	"runtime"
)

const (
	OUTPUT_TYPE_STDOUT = "stdout" // 日志输出模式-控制台输出
	OUTPUT_TYPE_FILE   = "file"   // 日志输出模式-文件输出
)

const (
	//# 日志级别; TRACE, DEBUG, INFO, WARN, ERROR, FATAL, PANIC
	LOGGER_LEVEL_TRACE = "TRACE"
	LOGGER_LEVEL_DEBUG = "DEBUG"
	LOGGER_LEVEL_INFO  = "INFO"
	LOGGER_LEVEL_WARN  = "WARN"
	LOGGER_LEVEL_ERROR = "ERROR"
	LOGGER_LEVEL_FATAL = "FATAL"
	LOGGER_LEVEL_PANIC = "PANIC"
)

// 初始化日志
func Setup() {

	if config.LOGGER_SETTING.OutputType == OUTPUT_TYPE_STDOUT {
		LOG.SetOutput(colorable.NewColorableStdout())
		LOG.Formatter = &logrus.TextFormatter{
			ForceColors:   true,
			FullTimestamp: false,
			CallerPrettyfier: func(frame *runtime.Frame) (function string, file string) {
				file = fmt.Sprintf(" %s:%d", frame.File, frame.Line)
				//function = fmt.Sprintf("%s:%d", frame.Function, frame.Line)
				return
			},
			DisableSorting: false,
		}
	} else if config.LOGGER_SETTING.OutputType == OUTPUT_TYPE_FILE {
		LOG.Formatter = &logrus.JSONFormatter{
			PrettyPrint: true,
		}
	} else {
		panic(errors.New("unsupport log output type:" + config.LOGGER_SETTING.OutputType))
	}

	switch config.LOGGER_SETTING.LogLevel {
	case LOGGER_LEVEL_TRACE:
		LOG.SetLevel(logrus.TraceLevel)
	case LOGGER_LEVEL_DEBUG:
		LOG.SetLevel(logrus.DebugLevel)
	case LOGGER_LEVEL_INFO:
		LOG.SetLevel(logrus.InfoLevel)
	case LOGGER_LEVEL_WARN:
		LOG.SetLevel(logrus.WarnLevel)
	case LOGGER_LEVEL_ERROR:
		LOG.SetLevel(logrus.ErrorLevel)
	case LOGGER_LEVEL_FATAL:
		LOG.SetLevel(logrus.FatalLevel)
	case LOGGER_LEVEL_PANIC:
		LOG.SetLevel(logrus.PanicLevel)
	default:
		panic(errors.New("unsupport log level:" + config.LOGGER_SETTING.LogLevel))
	}

	LOG.SetReportCaller(true)

	// 设置标准输出的output为logrus
	log.SetOutput(LOG.Writer())

}
